import {MyMap} from "../../../utils/lodash";

function isInPath(x, y) {
    var ctx = this.ctx
    ctx.beginPath();
    var dom = this.dom
    var all_width = dom.width
    var all_height = dom.height
    ctx.rect(0, 0, all_width, all_height);
    return ctx.isPointInPath(x, y);
}

class Stage {
    constructor(dom) {
        this.dom = dom
        this.ctx = this.dom.getContext("2d");
        this.children = []
        window.TAI_CANVAS = this.dom
        /*初始化 事件*/
        this.bindEvent()
    }

    bindEvent() {
        var dom = this.dom
        var children = this.children
        /*点击 事件*/
        dom.addEventListener('click', function (e) {
            MyMap(children, child => {
                if (child.onClick && child.isInPath(e.offsetX, e.offsetY)) {
                    child.onClick(e.offsetX, e.offsetY)
                }
            })
        })
        /*鼠标 下*/
        dom.addEventListener('mousedown', function (e) {
            MyMap(children, child => {
                if (child.isDragAble && child.isInPath(e.offsetX, e.offsetY)) {
                    child._mousedown(e.offsetX, e.offsetY)
                }
            })
        })
        /*鼠标 移动*/
        dom.addEventListener('mousemove', function (e) {
            MyMap(children, child => {
                if (child.isDragAble && child.isInPath(e.offsetX, e.offsetY)) {
                    child._mousemove(e.offsetX, e.offsetY)
                }
            })
        })
        /*鼠标 上*/
        dom.addEventListener('mouseup', function (e) {
            MyMap(children, child => {
                if (child.isDragAble && child.isInPath(e.offsetX, e.offsetY)) {
                    child._mouseup(e.offsetX, e.offsetY)
                }
            })
        })
    }

    add(obj) {
        var ctx = this.ctx
        obj.drawing && obj.drawing()
        ctx.beginPath();
        ctx.restore();
        this.children.push(obj)
        ctx.save();
    }
}

export default Stage